package com.hengpeng.itfints.controller.member;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.util.StringHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.util.DES;
import com.hengpeng.common.util.SignatureHelper;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.en.RewardRedPacketStatus;
import com.hengpeng.itfinbase.en.TransType;
import com.hengpeng.itfinbase.en.UserAppStatus;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.partner.PartnerTransType;
import com.hengpeng.itfinbase.message.partner.QueryCardInfoRequestMsg;
import com.hengpeng.itfinbase.message.partner.QueryCardInfoResponseMsg;
import com.hengpeng.itfinbase.message.userInfo.UserInfoResponse;
import com.hengpeng.itfinbase.persist.Account;
import com.hengpeng.itfinbase.persist.AccountLog;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfinbase.persist.UserInfo.RegionalType;
import com.hengpeng.itfinbase.persist.UserInfo.UserInfoType;
import com.hengpeng.itfinbase.persist.UserInfo.UserQuestionType;
import com.hengpeng.itfinbase.persist.UserTypeApply;
import com.hengpeng.itfinbase.persist.VerifyCode.VerifyType;
import com.hengpeng.itfints.controller.BaseController;
import com.hengpeng.itfints.controller.investInfo.vo.InvestInfoVo;
import com.hengpeng.itfints.tools.PageUtil;
import com.hengpeng.itfints.vo.MemberSession;

/**
 * <pre>
 * 会员中心控制类
 * </pre>
 * 
 * @author weiyuan
 * @version 1.0, 2015年7月6日
 */
@Controller
@RequestMapping("/memberCenter")
public class MemberCenterController extends BaseController {
    protected Log logger = LogFactory.getLog(this.getClass());

    /**
     * <pre>
     * 账户总览
     * </pre>
     * 
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/index")
    public String index(ModelMap map, HttpServletRequest request) {
        UserInfo m = getSessionMember(request).getUser();
        UserInfo user = serviceFactory.getUserService().getUserById(m.getId());
        if (StringHelper.isEmpty(user.getTrustAccountId())) {
            return "redirect:/step_two_register_active.htm";
        }
        Account account = serviceFactory.getAccountService().getAccount(m.getId());
        
        //投资概况
        InvestInfoVo investConstruction = serviceFactory.getInvestInfoService().getInvestConstruction(m.getId());
        // 红包总额
        RewardRedPacketStatus[] status = { RewardRedPacketStatus.CANUSE };
        String redpacketTotalAmount = serviceFactory.getActivityService()
                .getRegRedpacketTotalAmountByUserNameAndStatus(m.getId(), status);

        map.put("redpacketTotalAmount", redpacketTotalAmount);
        map.put("account", account);
        map.put("investConstruction", investConstruction);
        return "/page/account/index.jsp";
    }

    public class AmountAndTotalMoney {
        private String investingAmount = "0";
        private String investingTotalMoney = "0";

        public AmountAndTotalMoney() {
        }

        public AmountAndTotalMoney(String investingAmount, String investingTotalMoney) {
            this.investingAmount = investingAmount;
            this.investingTotalMoney = investingTotalMoney;
        }

        public String getInvestingAmount() {
            return investingAmount;
        }

        public void setInvestingAmount(String investingAmount) {
            this.investingAmount = investingAmount;
        }

        public String getInvestingTotalMoney() {
            return investingTotalMoney;
        }

        public void setInvestingTotalMoney(String investingTotalMoney) {
            this.investingTotalMoney = investingTotalMoney;
        }

    }

    /**
     * <pre>
     * 我的资金明细
     * </pre>
     * 
     * @param map
     * @param request
     * @param type
     * @param status
     * @param queryTime
     * @return
     */
    @RequestMapping(value = "/myAccountLogList")
    public String myAccountLogList(ModelMap map, HttpServletRequest request, TransType type, String queryTime,
            String curPage) {
        int int_curPage = (!StringHelper.isEmpty(curPage) ? Integer.parseInt(curPage) : 1);

        UserInfo m = getSessionMember(request).getUser();
        UserInfo user = serviceFactory.getUserService().getUserById(m.getId());
        if (StringHelper.isEmpty(user.getTrustAccountId())) {
            return "redirect:/step_two_register_active.htm";
        }
        Account account = serviceFactory.getAccountService().getAccount(m.getId());
        ServiceResult<List<AccountLog>> serviceResult = serviceFactory.getAccountService().queryAccountLogList(
                m.getId(), type, queryTime, int_curPage, 10);
        PageUtil pUtil = new PageUtil(10, serviceResult.getReturnListSize(), int_curPage);
        map.put("myAccountLogList", serviceResult.getReturnValue());
        map.put("account", account);
        map.put("type", type);
        map.put("queryTime", StringHelper.isEmpty(queryTime) ? "one_week" : queryTime);
        map.put("PageUtil", pUtil);
        return "/page/account/moneyhistory/index.jsp";
    }

    /**
     * <pre>
     * 银行卡管理
     * </pre>
     * 
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/cardManager")
    public String cardManager(ModelMap map, HttpServletRequest request) {
        UserInfo m = getSessionMember(request).getUser();
        QueryCardInfoRequestMsg queryCardInfoRequestMsg = new QueryCardInfoRequestMsg();
        queryCardInfoRequestMsg.setUserName(m.getUserName());
        queryCardInfoRequestMsg.setUsrCustId(m.getTrustAccountId());
        queryCardInfoRequestMsg.setPartnerTransType(PartnerTransType.QueryCardInfo);
        queryCardInfoRequestMsg.setBgRetUrl(service_notify_url);
        queryCardInfoRequestMsg.setRetUrl(page_return_url);
        queryCardInfoRequestMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
        QueryCardInfoResponseMsg queryCardInfoResponseMsg = (QueryCardInfoResponseMsg) serviceFactory.getProtFactory()
                .remoteTrans(queryCardInfoRequestMsg);
        map.put("UsrCardInfolist", queryCardInfoResponseMsg.getUsrCardInfolist());
        map.put("userBankCardList", queryCardInfoResponseMsg.getUserBankCardlist());
        map.put("userInfo", m);
        return "/page/account/user/card/cardList.jsp";
    }

    /**
     * <pre>
     * 转向充值
     * </pre>
     * 
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/toImprest")
    public String toImprest(ModelMap map, HttpServletRequest request) {
        UserInfo userInfo = getSessionMember(request).getUser();
        if (userInfo != null) {
            Account account = serviceFactory.getAccountService().getAccount(userInfo.getId());
            map.put("account", account);
        }
        return "/page/account/recharge/index.jsp";
    }

    /**
     * <pre>
     * 转向提现
     * </pre>
     * 
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/toDraw")
    public String toDraw(ModelMap map, HttpServletRequest request) {
        UserInfo m = getSessionMember(request).getUser();
        QueryCardInfoRequestMsg queryCardInfoRequestMsg = new QueryCardInfoRequestMsg();
        queryCardInfoRequestMsg.setUserName(m.getUserName());
        queryCardInfoRequestMsg.setUsrCustId(m.getTrustAccountId());
        queryCardInfoRequestMsg.setPartnerTransType(PartnerTransType.QueryCardInfo);
        queryCardInfoRequestMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
        queryCardInfoRequestMsg.setBgRetUrl(service_notify_url);
        queryCardInfoRequestMsg.setRetUrl(page_return_url);
        QueryCardInfoResponseMsg queryCardInfoResponseMsg = (QueryCardInfoResponseMsg) serviceFactory.getProtFactory()
                .remoteTrans(queryCardInfoRequestMsg);

        map.put("isBindCard", queryCardInfoResponseMsg.getUsrCardInfolist() != null
                && queryCardInfoResponseMsg.getUsrCardInfolist().size() > 0 ? "1" : "0");

        Account account = serviceFactory.getAccountService().getAccount(m.getId());
        map.put("account", account);
        return "/page/account/withdrawmoney/index.jsp";
    }

    /**
     * <pre>
     * 转向个人设置
     * </pre>
     * 
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/toPersonSet")
    public String toPersonSet(ModelMap map, HttpServletRequest request) {

        MemberSession session = getSessionMember(request);
        if (session == null) {
            return returnErrorPage(map, "登录过期，请重新登录");
        }
        UserInfo user = session.getUser();
        if (user == null) {
            return returnErrorPage(map, "登录过期，请重新登录");
        }
        user = serviceFactory.getUserService().getUserByUserName(user.getUserName());
        refreshSessionMember(request);

        if (user == null) {
            return "/";
        }
        // 安全等级
        int checkCount = 0;
        if (user.getIsEmailCheck() == BoolValue.YES) {
            checkCount++;
        }
        if (user.getIsMobileCheck() == BoolValue.YES) {
            checkCount++;
        }
        if (user.getIsQuestionCheck() == BoolValue.YES) {
            checkCount++;
        }
        if (user.getIsRealNameCheck() == BoolValue.YES) {
            checkCount++;
        }
        user.setMobile(stringFormatePageShow(user.getMobile(), 3, 3));
        user.setEmail(stringFormatePageShow(user.getEmail(), 3, 6));
        user.setCardNumber(stringFormatePageShow(user.getCardNumber(), 6, 4));
        user.setUserName(stringFormatePageShow(user.getUserName(), 2, 2));
        map.put("checkCount", checkCount);
        map.put("questionType", UserInfo.UserQuestionType.values());
        map.put("userPageShow", user);
        return "/page/account/setup/index.jsp";
    }

    /**
     * 实名认证
     * 
     * @param request
     */
    @RequestMapping(value = "/realNameAuth")
    @ResponseBody
    public ServiceResult<String> realNameAuth(HttpServletRequest request, ModelMap map, String realName,
            String cardNumber) {
        ServiceResult<String> result = new ServiceResult<String>();
        MemberSession session = getSessionMember(request);
        if (session == null) {
            return validateFailure("登录过期，请重新登录");
        }
        UserInfo user = session.getUser();
        if (user == null) {
            return validateFailure("登录过期，请重新登录");
        }
        if (StringUtils.isEmpty(realName) || StringUtils.isEmpty(cardNumber)) {
            return validateFailure("参数为空");
        }
        UserInfoResponse response = this.serviceFactory.getUserService().realNameAuth(user.getUserName(), realName,
                cardNumber);
        if (response != null) {
            if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                result.setIsSuccess(true);
                result.setMessage("实名成功");
                refreshSessionMember(request);
            } else {
                return validateFailure(response.getRespDesc());
            }
        } else {
            return validateFailure("实名认证失败");
        }
        return result;
    }

    /**
     * 修改密码
     * 
     * @param request
     */
    @RequestMapping(value = "/updatePassword")
    @ResponseBody
    public ServiceResult<String> updatePassword(HttpServletRequest request, ModelMap map, String oldPassword,
            String password, String re_new_password) {
        ServiceResult<String> result = new ServiceResult<String>();
        MemberSession session = getSessionMember(request);
        if (session == null) {
            return validateFailure("登录过期，请重新登录");
        }
        UserInfo user = session.getUser();
        if (user == null) {
            return validateFailure("登录过期，请重新登录");
        }
        if (StringUtils.isEmpty(oldPassword) || StringUtils.isEmpty(password)) {
            return validateFailure("参数为空");
        }

        if (StringUtils.isEmpty(re_new_password)) {
            return validateFailure("确认密码不为空");
        }

        if (!password.equals(re_new_password)) {
            return validateFailure("新密码与确认密码不一致");
        }

        int pleng = password.length();
        if (pleng < 6 || pleng > 16) {
            return validateFailure("密码字符长度应为6-16之间");
        }
        UserInfoResponse response = this.serviceFactory.getUserService().updatePassword(user.getUserName(),
                oldPassword, password);
        if (response != null) {
            if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                result.setIsSuccess(true);
                result.setMessage("修改密码成功");
                refreshSessionMember(request);
            } else {
                return validateFailure(response.getRespDesc());
            }
        } else {
            return validateFailure("修改密码失败");
        }
        return result;
    }

    /**
     * 添加邮箱
     * 
     * @param request
     * @param email
     * @param password
     * @param newEmail
     * @param reNewEmail
     * @return
     */
    @RequestMapping(value = "/addEmail", method = RequestMethod.POST)
    @ResponseBody
    public ServiceResult<Object> addEmail(HttpServletRequest request, String email, String password, String newEmail,
            String reNewEmail) {
        MemberSession session = getSessionMember(request);
        if (session == null) {
            return validateFailure("登录过期，请重新登录");
        }
        UserInfo user = session.getUser();
        return serviceFactory.getUserService().addEmail(user.getUserName(), password, newEmail, reNewEmail);
    }

    /**
     * 修改邮箱
     * 
     * @param request
     * @param email
     * @param password
     * @param newEmail
     * @param reNewEmail
     * @return
     */
    @RequestMapping("/modifyEmail")
    @ResponseBody
    public ServiceResult<Object> modifyEmail(HttpServletRequest request, String email, String password,
            String newEmail, String reNewEmail) {
        MemberSession session = getSessionMember(request);
        if (session == null) {
            return validateFailure("登录过期，请重新登录");
        }
        UserInfo user = session.getUser();
        return serviceFactory.getUserService().updateEmail(user.getUserName(), password, email, newEmail, reNewEmail);
    }

    /**
     * 设置密保
     * 
     * @param request
     */
    @RequestMapping(value = "/doSetQuestion")
    @ResponseBody
    public ServiceResult<String> doSetQuestion(HttpServletRequest request, ModelMap map, String questionType,
            String answer) {
        ServiceResult<String> result = new ServiceResult<String>();
        MemberSession session = getSessionMember(request);
        if (session == null) {
            return validateFailure("登录过期，请重新登录");
        }
        UserInfo user = session.getUser();
        if (user == null) {
            return validateFailure("登录过期，请重新登录");
        }
        if (StringUtils.isEmpty(questionType) || StringUtils.isEmpty(answer)) {
            return validateFailure("参数为空");
        }

        UserInfoResponse response = this.serviceFactory.getUserService().doSetQuestion(user.getUserName(),
                questionType, answer);
        if (response != null) {
            if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                result.setIsSuccess(true);
                result.setMessage("设置密保成功");
                refreshSessionMember(request);
            } else {
                return validateFailure(response.getRespDesc());
            }
        } else {
            return validateFailure("设置密保失败");
        }
        return result;
    }

    /**
     * 修改安全问题
     * 
     * @param request
     */
    @RequestMapping(value = "/upSetQuestion")
    @ResponseBody
    public ServiceResult<String> upSetQuestion(HttpServletRequest request, ModelMap map, String questionTypeold,
            String answerold, String questionTypenew, String answernew) {
        ServiceResult<String> result = new ServiceResult<String>();
        MemberSession session = getSessionMember(request);
        if (session == null) {
            return validateFailure("登录过期，请重新登录");
        }
        UserInfo user = session.getUser();
        if (user == null) {
            return validateFailure("登录过期，请重新登录");
        }
        if (StringUtils.isEmpty(questionTypeold) || StringUtils.isEmpty(answerold)
                || StringUtils.isEmpty(questionTypenew) || StringUtils.isEmpty(answernew)) {
            return validateFailure("参数为空");
        }
        user = serviceFactory.getUserService().getUserByUserName(user.getUserName());
        if (user.getQuestionType() != UserQuestionType.valueOf(questionTypeold)) {
            return validateFailure("老安全问题错误");
        }
        if (!answerold.equals(user.getAnswer())) {
            return validateFailure("老安全问题答案错误");
        }
        UserInfoResponse response = this.serviceFactory.getUserService().doSetQuestion(user.getUserName(),
                questionTypenew, answernew);
        if (response != null) {
            if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                result.setIsSuccess(true);
                result.setMessage("修改密保成功");
                refreshSessionMember(request);
            } else {
                return validateFailure(response.getRespDesc());
            }
        } else {
            return validateFailure("修改密保失败");
        }
        return result;
    }

    @RequestMapping(value = "/toUpSetQuestion", method = RequestMethod.GET)
    public String toUpSetQuestion(HttpServletRequest request, ModelMap map) {
        MemberSession session = getSessionMember(request);
        if (session == null) {
            return returnErrorPage(map, "登录过期，请重新登录");
        }
        UserInfo user = session.getUser();
        if (user == null) {
            return returnErrorPage(map, "登录过期，请重新登录");
        }
        user = serviceFactory.getUserService().getUserByUserName(user.getUserName());
        // UserQuestionType.valueOf(user.getQuestionType());
        map.put("oldQuestion", user.getQuestionType().getText());
        map.put("oldQuestionName", user.getQuestionType().name());
        return "/page/account/ProtectPwd/modifyProjectPwd.jsp";
    }

    /**
     * 邮箱验证发送邮件
     * 
     * @param request
     * @param email
     *            邮箱
     * @param validCode
     *            验证码
     * @param returnUrl
     * @return
     */
    @RequestMapping(value = "/sendValidEmail")
    @ResponseBody
    public ServiceResult<?> sendValidEmail(HttpServletRequest request, String email, String returnUrl) {

        ServiceResult<String> result = new ServiceResult<String>();
        MemberSession session = getSessionMember(request);
        if (session == null) {
            return validateFailure("登录过期，请重新登录");
        }
        UserInfo user = session.getUser();
        if (user == null) {
            return validateFailure("登录过期，请重新登录");
        }
        if (StringUtils.isEmpty(email)) {
            return validateFailure("参数为空");
        }
        StringBuffer url = new StringBuffer();
        url.append(request.getScheme());
        url.append("://");
        url.append(request.getServerName());
        url.append(":");
        url.append(request.getServerPort());
        url.append(request.getContextPath());
        url.append("/memberCenter/doValidEmail.htm");
        ResponseMessage response = serviceFactory.getUserService().sendMailForValid(email, user.getUserName(), null,
                url.toString(), returnUrl, null);
        if (response != null) {
            if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                result.setIsSuccess(true);
                result.setMessage("已发送验证邮件");
                refreshSessionMember(request);
            } else {
                return validateFailure(response.getRespDesc());
            }
        } else {
            return validateFailure("发送验证邮件失败");
        }
        return result;
    }

    /**
     * 邮箱验证发送邮件
     * 
     * @param request
     * @param email
     *            邮箱
     * @param validCode
     *            验证码
     * @param returnUrl
     * @return
     */
    @RequestMapping(value = "/sendValidEmailCX")
    @ResponseBody
    public ServiceResult<?> sendValidEmailCX(HttpServletRequest request, String oldemail, String newemail,
            String returnUrl) {
        ServiceResult<String> result = new ServiceResult<String>();
        MemberSession session = getSessionMember(request);
        if (session == null) {
            return validateFailure("登录过期，请重新登录");
        }
        UserInfo user = session.getUser();
        if (user == null) {
            return validateFailure("登录过期，请重新登录");
        }
        if (StringUtils.isEmpty(oldemail) || StringUtils.isEmpty(newemail)) {
            return validateFailure("参数为空");
        }
        StringBuffer url = new StringBuffer();
        url.append(request.getScheme());
        url.append("://");
        url.append(request.getServerName());
        url.append(":");
        url.append(request.getServerPort());
        url.append(request.getContextPath());
        url.append("/memberCenter/doValidEmail.htm");
        ResponseMessage response = serviceFactory.getUserService().sendMailForValid(newemail, user.getUserName(), null,
                url.toString(), returnUrl, null);
        if (response != null) {
            if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                result.setIsSuccess(true);
                result.setMessage("已发送验证邮件");
                refreshSessionMember(request);
            } else {
                return validateFailure(response.getRespDesc());
            }
        } else {
            return validateFailure("发送验证邮件失败");
        }
        return result;
    }

    /**
     * 邮箱验证邮件确认
     * 
     * @param validCode
     *            验证码
     * @param request
     * @param type
     *            访问类型
     * @param modelMap
     * @param username
     *            用户名称
     * @param verifyCode
     *            验证码
     * @param email
     *            邮箱
     * @return
     */
    @RequestMapping(value = "/doValidEmail")
    public String doValidEmail(HttpServletRequest request, String successUrl, String errorUrl, ModelMap modelMap,
            String username, String verifyCode, String email) {

        String message = "";
        try {
            DES des = new DES();
            username = des.decrypt(username);
            email = des.decrypt(email);
            successUrl = des.decrypt(successUrl);
            errorUrl = des.decrypt(errorUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        MemberSession session = getSessionMember(request);
        if (session == null) {
            modelMap.put("valid_Email_Message", "登录过期，请重新登录");
            return errorUrl;
        }
        UserInfo user = session.getUser();
        if (user == null) {
            modelMap.put("valid_Email_Message", "登录过期，请重新登录");
            return errorUrl;
        }
        UserInfo user2 = serviceFactory.getUserService().getUserByUserName(username);
        if (user2 == null) {
            modelMap.put("valid_Email_Message", "此链接无效");
            return errorUrl;
        }
        if (user.getUserName().equals(username)) {
            ResponseMessage response = serviceFactory.getUserService().doValidEmail(username, verifyCode, email);
            if (response != null) {
                if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                    message = "邮箱绑定成功";
                } else {
                    message = response.getRespDesc();
                }
            }
        } else {
            message = "此链接无效";
        }
        successUrl = ((successUrl == null || successUrl.length() < 1) ? "/memberCenter/toPersonSet.htm" : successUrl);
        modelMap.put("valid_Email_Message", message);
        refreshSessionMember(request);
        return successUrl;
    }

    /**
     * 手机验证发送短信
     * 
     * @return
     */
    @RequestMapping(value = "/sendValidSMS")
    @ResponseBody
    public ServiceResult<Long> sendValidSMS(HttpServletRequest request, String mobile) {
        ServiceResult<Long> result = new ServiceResult<Long>();
        UserInfo user = serviceFactory.getUserService().getUserByMobile(mobile);
        if (user != null) {
            return validateFailure("新手机号码已经存在");
        }
        MemberSession session = getSessionMember(request);
        if (session == null) {
            return validateFailure("登录过期，请重新登录");
        }
        user = session.getUser();
        if (user == null) {
            return validateFailure("登录过期，请重新登录");
        }
        if (StringUtils.isEmpty(mobile)) {
            return validateFailure("参数为空");
        }
        Object sendTime = request.getSession().getAttribute("SMSTIME");
        long timeInterval = 30l;
        long nowTime = Calendar.getInstance().getTimeInMillis();
        if (sendTime == null) {
            request.getSession().setAttribute("SMSTIME", nowTime);
        } else {
            long countDown = nowTime - Long.parseLong(String.valueOf(sendTime));
            if (countDown >= 1000 * timeInterval) {
                request.getSession().setAttribute("SMSTIME", nowTime);
            } else {
                return validateFailure((timeInterval - countDown / 1000) + "s后，才能再次发送短信验证码");
            }
        }
        ResponseMessage response = serviceFactory.getUserService().sendSMSForValidMobile(user.getUserName(), mobile,
                null, VerifyType.VALIDMOBILE);
        if (response != null) {
            if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                result.setIsSuccess(true);
                result.setMessage("发送验证短信成功");
                result.setReturnValue(timeInterval);
            } else {
                return validateFailure(response.getRespDesc());
            }
        } else {
            return validateFailure("发送验证短信失败");
        }
        return result;
    }

    /**
     * 获取可以再次发送短信的时间
     * 
     * @return
     */
    @RequestMapping(value = "/getSendTime")
    @ResponseBody
    public ServiceResult<Long> getSendTime(HttpServletRequest request) {
        ServiceResult<Long> result = new ServiceResult<Long>();
        Object sendTime = request.getSession().getAttribute("SMSTIME");
        if (sendTime == null) {
            result.setIsSuccess(false);
            result.setReturnValue(-1L);
        } else {
            long nowTime = Calendar.getInstance().getTimeInMillis();
            long countDown = nowTime - Long.parseLong(String.valueOf(sendTime));
            long timeInterval = 30l;
            if (countDown >= 1000 * timeInterval) {
                request.getSession().removeAttribute("SMSTIME");
                result.setReturnValue(-1L);
            } else {
                result.setReturnValue(timeInterval - countDown / 1000);
            }
        }
        return result;
    }

    /**
     * 手机验证绑定
     * 
     * @param request
     * @param mobile
     *            手机号
     * @param code
     *            短信验证码
     * @return
     */
    @RequestMapping(value = "/doValidSMS")
    @ResponseBody
    public ServiceResult<Long> doValidSMS(HttpServletRequest request, String mobile, String code) {
        ServiceResult<Long> result = new ServiceResult<Long>();
        UserInfo user = serviceFactory.getUserService().getUserByMobile(mobile);
        if (user != null) {
            return validateFailure("新手机号码已经存在");
        }
        MemberSession session = getSessionMember(request);
        if (session == null) {
            return validateFailure("登录过期，请重新登录");
        }
        user = session.getUser();
        if (user == null) {
            return validateFailure("登录过期，请重新登录");
        }
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(code)) {
            return validateFailure("参数为空");
        }
        ResponseMessage response = serviceFactory.getUserService().doValidMobile(user.getUserName(), mobile, code,
                VerifyType.VALIDMOBILE);
        if (response != null) {
            if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                ResponseMessage bingMes = serviceFactory.getUserService().bingMobile(user.getUserName(), mobile);
                if (RespCodeConstants.CommonCode.TRANS_SUC.equals(bingMes.getRespCode())) {
                    result.setIsSuccess(true);
                    result.setMessage("修改手机绑定成功");
                } else {
                    return validateFailure(bingMes.getRespDesc());
                }
            } else {
                return validateFailure(response.getRespDesc());
            }
        } else {
            return validateFailure("修改手机绑定失败");
        }
        refreshSessionMember(request);
        return result;
    }

    /**
     * 邀请返利页面
     */
    @RequestMapping(value = "/recommendCode")
    public String getRecommendCodePage(HttpServletRequest request, ModelMap map) {
        MemberSession session = getSessionMember(request);
        if (session == null) {
            return "/page/login/login.jsp";
        }
        UserInfo user = serviceFactory.getUserService().getUserById(session.getUser().getId());
        if (StringHelper.isEmpty(user.getTrustAccountId())) {
            return "redirect:/step_two_register_active.htm";
        }
        String recommendCode = session.getUser().getRecommendCode();
        map.put("recommendCode", recommendCode);
        return "/page/account/reward/recommendcode.jsp";
    }

    /**
     * 跳转至升级账户申请页面
     * 
     * @param request
     * @param map
     * @return
     */
    @RequestMapping(value = "/upgradeUser")
    public String UpgradeUser(HttpServletRequest request, ModelMap map) {
        MemberSession session = getSessionMember(request);
        if (session == null) {
            return "/page/login/login.jsp";
        }
        return "/page/account/upgrade/index.jsp";
    }

    /**
     * 跳转至升级账户审核
     * 
     * @param request
     * @param map
     * @return
     */
    @RequestMapping(value = "/lastUpgrate")
    public String lastUpgrate(HttpServletRequest request, ModelMap map) {
        MemberSession session = getSessionMember(request);
        if (session == null) {
            return "/page/login/login.jsp";
        }
        Long id = session.getUser().getId();
        DynamicQuery query = new DynamicQuery(UserTypeApply.class);
        query.eq("userId", id);
        query.desc("createTime");
        query.setPageIndex(1);
        query.setPageSize(1);
        UserTypeApply entity = serviceFactory.getPersistService().getEntity(query, UserTypeApply.class);
        map.put("entity", entity);
        map.put("userTypeName", entity.getAppUserInfoType().getText());
        return "/page/account/upgrade/next_result.jsp";
    }

    /**
     * 升级账户申请
     * 
     * @param request
     * @param map
     * @return
     */
    @RequestMapping(value = "/nextUpgrade")
    @ResponseBody
    public ServiceResult<Long> nextUpgrade(HttpServletRequest request, String userType, String password, ModelMap map,
            String regionalType) {
        MemberSession session = getSessionMember(request);
        String mess = "";
        String password2 = session.getUser().getPassword();
        Long id = session.getUser().getId();
        UserInfo user = serviceFactory.getPersistService().get(UserInfo.class, id);
        password = SignatureHelper.generateMD5Signture(password + user.getPwdAttach(), "utf-8");
        if (!password2.equalsIgnoreCase(password)) {
            mess = "1";
        } else {// 添加账户升级记录
            UserTypeApply userTypeApply = new UserTypeApply();
            userTypeApply.setCreateTime(new Date());
            userTypeApply.setUserId(id);
            userTypeApply.setAppUserInfoType(UserInfoType.valueOf(userType));
            userTypeApply.setUserApplyStatus(UserAppStatus.PASSING);
            userTypeApply.setRegionalType(RegionalType.valueOf(regionalType));
            serviceFactory.getPersistService().save(userTypeApply);
            serviceFactory.getUserService().updateRealName(id, regionalType);
            mess = "2";
        }
        ServiceResult<Long> result = new ServiceResult<Long>();
        result.setMessage(mess);
        return result;

    }

    private String stringFormatePageShow(String s, int startLength, int endLength) {
        try {
            if (StringUtils.isEmpty(s) || s.length() <= 4) {
                return s;
            } else {
                return s.substring(0, startLength) + "****" + s.substring(s.length() - endLength, s.length());
            }
        } catch (Exception e) {
            return s;
        }

    }
}
